const { Service } = require("egg");
class GoodsService extends Service {
  // 新增商品
  async addGoods(payload) {
    const { ctx } = this;
    const { _id, categoryId, image, name, description, attribute, price, small, stock, recommend, type, checkedkeys } =
      payload;
    const query = { categoryId, image, name, description, attribute, price, small, stock, recommend, type, checkedkeys };
    let goodsInfo;
    if (_id) {
      goodsInfo = await ctx.model.Goods.findByIdAndUpdate( _id , query);
    } else {
      goodsInfo = await ctx.model.Goods.create(query);
    }
    return { msg: "成功", data: goodsInfo };
  }
  // 获取商品列表
  async getGoodsList(pages = 1, sizes = 20) {
    const { ctx } = this;
    const db = ctx.model.Goods;
    const page = Number(pages);
    const size = Number(sizes);
    const res = await db.aggregate([
      {
        $limit: size,
      },
      {
        $skip: (page - 1) * size,
      },
      {
        $lookup: {
          from: "Category",
          localField: "categoryId",
          foreignField: "_id",
          as: "category",
        },
      },
      {
        $unwind: "$category", // $unwind将category数组中的每一个元素拆分成一个文档
      },

    ]);
    const total = await db.countDocuments();
    return {
      data: {
        list: res,
        page,
        size,
        total,
      },
      msg: "成功",
    };
  }
  //  删除商品
  async delGoods(_id) {
    const { ctx } = this;
    await ctx.model.Attrdetail.deleteMany({ goodsId: _id });
    await ctx.model.Goods.deleteOne({ _id });
    return {
      msg: "成功",
    };
  }
  // 模糊查询商品
  async searchGoodsList(keyword) {
    const { ctx } = this;
    const query = { $regex: keyword, $options: "i" };
    const res = await ctx.model.Goods.find({
      $or: [{ name: query }, { description: query }],
    });
    return { msg: "成功", data: res };
  }
}
module.exports = GoodsService;
